package com.gs.wzmanager.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gs.wzmanager.bo.DSBeanTypeToken;
import com.gs.wzmanager.bo.ForeDayTypeToken;
import com.gs.wzmanager.dao.ForeDayDao;
import com.gs.wzmanager.entity.DSBean;
import com.gs.wzmanager.service.ForeService;
import com.gs.wzmanager.utils.Constant;
import com.gs.wzmanager.utils.DateUtil;
import com.gs.wzmanager.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/*

 */
@Service
public class ForeServiceImpl implements ForeService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    Gson gson = new Gson();

    @Autowired
    ForeDayDao foreDayDao;

    @Override
    public List<DSBean> queryPortFore(String station) {
        List<DSBean> fore7Result = foreDayDao.queryPortFore(station);
        if (fore7Result == null || fore7Result.size() == 0) {
            fore7Result = get3OR7ForeDay(station, true);
        }
        return fore7Result;
    }

    @Override
    public List<DSBean> queryChannelFore(String station) {
        List<DSBean> fore3Result = foreDayDao.queryChannelFore(station);
        if (fore3Result == null || fore3Result.size() == 0) {
            fore3Result = get3OR7ForeDay(station, false);
        }
        return fore3Result;
    }

    @Override
    public ResponseEntity addPortFore(List<DSBean> dsBeans, String stationName) {
        if (foreDayDao.addPortFore(dsBeans)) {
            createFile(dsBeans, stationName);
            return HttpUtils.buildStringResponse("OK", HttpStatus.OK);
        } else return HttpUtils.buildStringResponse("ERR", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    public ResponseEntity addChannelFore(List<DSBean> dsBeans, String stationName) {
        if (foreDayDao.addChannelFore(dsBeans)) {
            createFile(dsBeans, stationName);
            return HttpUtils.buildStringResponse("OK", HttpStatus.OK);
        } else return HttpUtils.buildStringResponse("ERR", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    public ResponseEntity updatePortFore(List<DSBean> dsBeans, String stationName) {
        if (foreDayDao.updatePortFore(dsBeans)) {
            createFile(dsBeans, stationName);
            return HttpUtils.buildStringResponse("OK", HttpStatus.OK);
        } else return HttpUtils.buildStringResponse("ERR", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    public ResponseEntity updateChannelFore(List<DSBean> dsBeans, String stationName) {
        if (foreDayDao.updateChannelFore(dsBeans)) {
            createFile(dsBeans, stationName);
            return HttpUtils.buildStringResponse("OK", HttpStatus.OK);
        } else return HttpUtils.buildStringResponse("ERR", HttpStatus.INTERNAL_SERVER_ERROR);
    }

     /*
        winds：风速
        windd：风向
        pr24：24小时降水量
        t：温度
        ww12:12小时天气
     */

    public List<DSBean> get3OR7ForeDay(String staId, boolean isPort) {
        List<DSBean> result = new ArrayList<>();
        String element = "winds,windd,t,pr24,ww12";
        try {
            String response = HttpUtils.request(Constant.Url.FORE_7_DAY + Constant.Url.PARAM_STAID + staId + Constant.Url.PARAM_ELEMENT + element);
            logger.info("get3OR7ForeDay->{}", response);
            ForeDayTypeToken foreDayTypeToken = gson.fromJson(response, new TypeToken<ForeDayTypeToken>() {
            }.getType());
            if (foreDayTypeToken.getReturnCode() == 0) {
                List<DSBeanTypeToken> ds = foreDayTypeToken.getDS();
                for (int i = 1; i < ds.size(); i++) {
                    if (i % 2 != 0) {
                        DSBeanTypeToken dsTem = ds.get(i);
                        DSBean bean = new DSBean(staId, foreDayTypeToken.getTime(), dsTem.getPr24().equals("-999.0") ? "0.0" : dsTem.getPr24(), dsTem.getHours(), dsTem.getWindd(), dsTem.getT(), dsTem.getWinds(), dsTem.getWw12().equals("-999.0") ? "0.0" : dsTem.getWw12());
                        if (isPort) {
                            if (result.size() < 7) {
                                result.add(bean);
                            }
                        } else {
                            if (result.size() < 3) {
                                result.add(bean);
                            }
                        }
                    }
                }
                return result;
            }
        } catch (Exception e) {
            logger.info("getFore7d->{}", e.getMessage());
        }
        return null;
    }

    public void createFile(List<DSBean> dsBeans, String stationName) {
        String dirName = Constant.FORECAST_PATH.PORTANDCHANNEL;
        File dir = new File(dirName);
        if (!dir.exists()) dir.mkdirs();

        String fileName = dirName + DateUtil.getYMDHMS() + stationName + ".txt";
        File file = new File(fileName);
        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            file.createNewFile();
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(stationName + "\r\n");
            for (int i = 0; i < dsBeans.size(); i++) {
                String content = "发布时间:" + dsBeans.get(i).getTime() +" "+
                        "未来时段:" + dsBeans.get(i).getHours() +" "+
                        "24小时降水:" + dsBeans.get(i).getPr24() +" "+
                        "风向:" + dsBeans.get(i).getWindd() +" "+
                        "风速:" + dsBeans.get(i).getWinds() +" "+
                        "温度:" + dsBeans.get(i).getT() +" "+
                        "天气现象:" + dsBeans.get(i).getWw12();
                pw.write(content + "\r\n");
            }
            pw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
